<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

/**
 * 课程回收站管理
 */
class Recyclebin extends Backend
{
    // 当前对象模型
    protected $model = null;

    // 设置关联模型的搜索功能
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Business.Business');
        // $this->ChapterModel = model('Subject.Chapter');
    }

    // 查看
    public function index()
    {
        if ($this->request->isAjax()) {

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->onlyTrashed()
                ->with('source')
                ->where($where)//deletetime
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->onlyTrashed()
                ->with('source')
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 还原
    public function reduction($ids = null)
    {
        $row = $this->model->onlyTrashed()->select($ids);

        if(!$row)
        {
            $this->error('课程不存在');
        }

        $result = $this->model->onlyTrashed()->where('id', 'IN', $ids)->update(['deletetime' => null]);

        // echo $this->model->getLastSql();exit;

        if(!$result)
        {
            $this->error($this->model->getError());
        }

        $this->success();
    }

    // 删除
    public function del($ids = null)
    {
        $row = $this->model->onlyTrashed()->select($ids);

        if(!$row)
        {
            $this->error('课程不存在');
        }

        // 查询所有章节视频地址   查询某一列的值
        $urllist = $this->ChapterModel->where('subid', 'IN', $ids)->column('url');

        $result = $this->model->destroy($ids, true);

        if(!$result)
        {
            $this->error($this->model->getError());
        }
        // 删除课程的所有图片
        foreach ($row as $item)
        {
            is_file(trim($item['thumbs'], '/')) && unlink(trim($item['thumbs'], '/'));
        }

        // 删除章节所有视频
        foreach($urllist as $item)
        {
            is_file(trim($item, '/')) && unlink(trim($item, '/')); 
        }
        
        $this->success();
    }
}
